<template>
  <el-select class="search" v-model="role_id" placeholder="请选择角色">
    <el-option
      v-for="(item, index) in roleList"
      :key="index"
      :label="item.roleName"
      :value="item.roleId"
    ></el-option>
  </el-select>
  <el-button type="primary" icon="el-icon-search" @click="seachRole">
    查询
  </el-button>
  <el-button icon="el-icon-refresh">重置</el-button>
  <el-button icon="el-icon-plus" type="success" @click="addMenuBtn">
    新增
  </el-button>
  <br />
  <br />
  <el-table
    @selection-change="handleSelectionChange"
    :data="role.slice((currentPage - 1) * pageSize, currentPage * pageSize)"
    height="530"
    style="width: 100%"
  >
    <!-- <el-table-column type="selection"></el-table-column> -->
    <el-table-column prop="roleId" label="角色id"></el-table-column>
    <el-table-column prop="roleName" label="角色名称"></el-table-column>
    <el-table-column prop="remark" label="角色描述"></el-table-column>
    <el-table-column prop="createDate" label="创建日期"></el-table-column>
    <el-table-column prop="updateDate" label="更新日期"></el-table-column>
    <el-table-column prop="isDelete" label="状态">
      <template #default="scope">
        <el-button v-if="scope.row.isDelete == 0" type="success" size="small">
          已启用
        </el-button>
        <el-button v-else type="danger" size="small">已禁用</el-button>
      </template>
    </el-table-column>
    <el-table-column fixed="right" align="center" label="操作" min-width="150">
      <template #default="scope">
        <el-popconfirm hide-icon="true" :title="checkData">
          <template #reference>
            <el-button
              icon="el-icon-view"
              size="small"
              type="info"
              @click="check(scope.row)"
            ></el-button>
          </template>
        </el-popconfirm>
        <el-button
          icon="el-icon-edit"
          size="small"
          type="warning"
          @click="editrow(scope.row)"
        ></el-button>
        <el-button
          icon="el-icon-delete"
          size="small"
          type="danger"
          @click="deleterow(scope.row)"
        ></el-button>
      </template>
    </el-table-column>
  </el-table>
  <el-pagination
    v-model:current-page="currentPage"
    v-model:page-size="pageSize"
    :page-sizes="[5, 10, 15, 20, 30]"
    :size="default"
    :disabled="disabled"
    :background="background"
    layout="total, prev, pager, next,sizes"
    :total="role.length"
  />
  <el-dialog v-model="dialogFormVisible" title="角色管理" :width="450">
    <el-form style="padding: 20px" v-model="rowdata">
      <el-form-item label="角&ensp;色&ensp;ID" label-width="formLabelWidth">
        <el-input disabled autocomplete="off" v-model="rowdata.roleId" />
      </el-form-item>
      <el-form-item label="角色名称" :label-width="formLabelWidth">
        <el-select v-model="rowdata.roleId" placeholder="请选择角色">
          <el-option
            v-for="(item, index) in role"
            :key="index"
            :label="item.roleName"
            :value="item.roleId"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="角色描述" :label-width="formLabelWidth">
        <el-input autocomplete="off" v-model="rowdata.remark" />
      </el-form-item>
      <el-form-item label="路&emsp;&emsp;径" :label-width="formLabelWidth">
        <el-tree
          :props="defaultProps"
          :data="treeMenu"
          show-checkbox
          node-key="menuId"
          ref="tree"
          :default-expanded-keys="extendss"
          @check-change="handleCheckChange"
          :default-checked-keys="menus"
        >
          <template #default="{ node, data }">
            <span class="custom-tree-node">
              <span>{{ data.menuName }}</span>
            </span>
          </template>
        </el-tree>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="cancel()">取消</el-button>
        <el-button type="primary" @click="saveRole()">保存</el-button>
      </div>
    </template>
  </el-dialog>
  <el-dialog v-model="addDialogVisible" title="添加角色" :width="450">
    <el-form style="padding: 20px" ref="addForm" :model="rowdata">
      <el-form-item label="角色名称" label-width="formLabelWidth">
        <el-input autocomplete="off" v-model="newRole.roleName" />
      </el-form-item>
      <el-form-item label="角色描述" :label-width="formLabelWidth">
        <el-input autocomplete="off" v-model="newRole.remark" />
      </el-form-item>
      <el-form-item :label-width="formLabelWidth" style="text-align: center">
        <el-button @click="addDialogVisible = false">取消</el-button>
        &emsp;&emsp;
        <el-button type="success" @click="SubmitRole()">提交</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>
<script lang="ts" setup>
import {
  getMenu,
  getRole,
  getTreeMenu,
  selectRoleMenuByRoleId,
  saveRoles,
  addRole,
  deleteRoleById,
} from '@/api/role'
import { onMounted, ref } from 'vue'
import { ElMessageBox, ElMessage } from 'element-plus'
const defaultProps = { children: 'childrenList', label: 'menuName' }
var role_id = ref()
// var roleId = ref()
const menuList = ref()
const dialogFormVisible = ref(false)
const addDialogVisible = ref(false)
const checkData = ref('')
var pageSize = ref(5)
var currentPage = ref(1)
// var router = useRouter()
var menu = ref([])
var treeMenu = ref([])
var role = ref([])
const roleList = ref([])
// var value = ref('')
const rowdata = ref([])
// var sex = ref('0')
// var staut = ref('1')
var menus = ref([])
var result = ref(false)
var newRole = ref({
  roleName: '',
  remark: '',
})
const handleCheckChange = (
  data: Tree,
  checked: boolean,
  indeterminate: boolean
) => {
  console.log(data, checked, indeterminate)
  // rowdata.value.menus.splice(0,1)
  if (checked) {
    rowdata.value.menus.push(data)
    console.log(11111111111)
    console.log(rowdata.value.menus)
  } else {
    var index = rowdata.value.menus.findIndex(
      item => item.menuId === data.menuId
    )
    rowdata.value.menus.splice(index, 1)
    console.log(222222)
    console.log(rowdata.value.menus)
  }
}
const handleSelectionChange = val => {
  // console.log(val.map((item) => item.menu_id));
  menuList.value = val.map(item => item.menuId)
}

onMounted(async () => {
  menu.value = (await getMenu()).data
  roleList.value = (await getRole()).data
  role.value = (await getRole(role_id.value)).data
  treeMenu.value = (await getTreeMenu()).data
  // console.log(menu.value)
  // console.log(role.value)
})
async function SubmitRole() {
  addDialogVisible.value = false
  result.value = (
    await addRole(newRole.value.roleName, newRole.value.remark)
  ).data
  if (result.value) {
    ElMessage({
      type: 'success',
      message: '添加成功',
    })
    location.reload()
  } else {
    ElMessage({
      type: 'error',
      message: '添加失败',
      duration: 500,
      onClose: () => {
        location.reload()
      },
    })
  }
}
async function seachRole() {
  // alert(role_id.value)
  role.value = (await getRole(role_id.value)).data
}
function check(row) {
  checkData.value =
    '角色ID：' +
    row.roleId +
    '\n角色名称：' +
    row.roleName +
    '\n角色描述：' +
    row.remark +
    '\n创建日期：' +
    row.createDate +
    '\n更新日期：' +
    row.updateDate +
    '\n状态：' +
    (row.isDelete == 0 ? ' 正常' : ' 删除')
}
function addMenuBtn() {
  rowdata.value = []
  addDialogVisible.value = true
}
function cancel() {
  dialogFormVisible.value = false
  menus.value = []
}
async function saveRole() {
  dialogFormVisible.value = false
  // console.log(menus.value);
  // rowdata.value.menus = menus.value
  result.value = (await saveRoles(JSON.stringify(rowdata.value))).data
  menus.value = []
  if (result.value) {
    ElMessage({
      type: 'success',
      message: '保存成功',
    })
    location.reload()
  } else {
    ElMessage({
      type: 'error',
      message: '保存失败',
      duration: 500,
      onClose: () => {
        location.reload()
      },
    })
  }
}
async function editrow(row) {
  // roleId.value = row.roleId
  console.log(row)
  rowdata.value = row
  menus.value = (await selectRoleMenuByRoleId(row.roleId)).data
  // alert(menus.value)
  dialogFormVisible.value = true
}
function SubmitMenu() {
  console.log('提交数据')
  addDialogVisible.value = false
}
async function deleterow(row) {
  ElMessageBox.confirm('确定要删除' + row.roleName + '角色吗？', 'Warning', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    result.value = (await deleteRoleById(row.roleId)).data
    // console.log(result.value);
    if (result.value) {
      ElMessage({
        type: 'success',
        message: '删除成功',
      })
      location.reload()
    } else {
      ElMessage({
        type: 'error',
        message: '删除失败',
        duration: 500,
        onClose: () => {
          location.reload()
        },
      })
    }
  })
}
</script>
<style>
.search {
  width: 15%;
  margin-bottom: 20px;
  margin-right: 20px;
}
.el-table__body tr:hover > td {
  background-color: #d7eff6 !important;
  /* color: #f19944; */ /* 设置文字颜色，可以选择不设置 */
}
.el-popconfirm__main {
  white-space: pre-line;
  padding: 10px;
}
</style>
